package com.dormitory.httpHelper;

import com.dormitory.staticVariable.StaticVariable;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by hhtt on 2017/10/20.
 */

public class HttpAddNotification {
    public static int AddNotificationByGet(String title, String content, int dormitoryId,String ausername) throws IOException, JSONException {
        URL url = new URL(StaticVariable.AddNo_SERVLET);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setReadTimeout(5000);
        conn.setConnectTimeout(5000);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("title", title);
        jsonObject.put("content", content);
        jsonObject.put("dormitoryId", dormitoryId);
        jsonObject.put("ausername",ausername);
        OutputStream out = conn.getOutputStream();
        out.write(jsonObject.toString().getBytes());
        out.flush();
        out.close();
        conn.connect();
        if(conn.getResponseCode() == 200) {
            InputStream is = conn.getInputStream();
            BufferedReader bf = new BufferedReader(new InputStreamReader(is));
            String data = bf.readLine();
            if(data.equals("OK")) {
                return 0;
            }
            else if(data.equals("NULL")){
                return 1; //标题为空
            }
            else {
                return 3;//寝室不存在
            }
        }
        else
            return 2;   //网络错误
    }
}
